package com.ctrip.framework.apollo.demo.spring.springBootDemo.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author:gxd
 * @Description:
 * @Date: 8:55 2018/4/13
 * @Modified By:
 */
@Configuration
public class CacheConfig {
    private static final Logger logger = LoggerFactory.getLogger(SampleRedisConfig.class);

    @Autowired
    private SampleRedisConfig sampleRedisConfig;

    @RefreshScope
    @Bean(name="jedisCluster")
    public JedisCluster getJedisCluster() {
        String nodeStr = sampleRedisConfig.getClusterNodes();//获取服务器数组(这里要相信自己的输入，所以没有考虑空指针问题)
        String [] nodeArr = nodeStr.split(",");
        Set<HostAndPort> nodes = new HashSet<>();

        for (String node : nodeArr) {
            String[] ipPortPair = node.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        return new JedisCluster(nodes,sampleRedisConfig.getCommandTimeout(),sampleRedisConfig.getMaxAttempts(),new GenericObjectPoolConfig());
    }


    @RefreshScope
    @Bean(name="jedisPoolConfig")
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(sampleRedisConfig.getMaxIdle());
        jedisPoolConfig.setMinIdle(sampleRedisConfig.getMinIdle());
            //超时时间
        jedisPoolConfig.setMaxWaitMillis(sampleRedisConfig.getMaxWaitMillis());
        jedisPoolConfig.setTestOnBorrow(sampleRedisConfig.getTestOnBorrow());
        jedisPoolConfig.setTestOnReturn(sampleRedisConfig.getTestOnReturn());
        return jedisPoolConfig;
    }
    @RefreshScope
    //@Scope(proxyMode = ScopedProxyMode.NO)
    @Bean(name="redisConnectionFactory")
    public JedisConnectionFactory redisConnectionFactory(@Qualifier("jedisPoolConfig") JedisPoolConfig jedisPoolConfig) {
        if(sampleRedisConfig.getClusterNodes()!= null && sampleRedisConfig.getClusterNodes().contains(",")){
            RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(Arrays.asList(sampleRedisConfig.getClusterNodes().split(",")));
            redisClusterConfiguration.setMaxRedirects(sampleRedisConfig.getMaxRedirects());
            logger.debug("load redis cluster success {} ", sampleRedisConfig.getClusterNodes().toString());
            return new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig);
        }else{
            JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
            redisConnectionFactory.setHostName(sampleRedisConfig.getHost());
            redisConnectionFactory.setPort(sampleRedisConfig.getPort());
            redisConnectionFactory.setTimeout(sampleRedisConfig.getTimeout());
            redisConnectionFactory.setPassword(sampleRedisConfig.getPassword());
            redisConnectionFactory.setDatabase(sampleRedisConfig.getDatabase());
            redisConnectionFactory.setPoolConfig(jedisPoolConfig);
            logger.debug("load redis single success {} ", sampleRedisConfig.getHost().toString());
            return redisConnectionFactory;
        }
    }

    @RefreshScope
    @Bean(name="sessionRedisTemplate")
    public RedisTemplate<Object, Object> sessionRedisTemplate(@Qualifier("redisConnectionFactory") JedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        logger.debug("sessionRedisTemplate 初始化成功......");
        return template;
    }
    @RefreshScope
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(@Qualifier("redisConnectionFactory") JedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        logger.debug("redisTemplate 初始化成功......");
        return template;
    }
}
